package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.UserContext;
import cn.wolfcode.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Notice notice) {
        notice.setEmployee(UserContext.getEmployee());
        notice.setCreateTime(new Date());
        //保存的状态是 未发布 只有点击发布 状态才会变成发布
        notice.setStatus(false);
        //因为第一次发布所以是 未读的
        notice.setIsRead(false);
        noticeMapper.insert(notice);

        //添加了公告后 要在中间表插入数据
        // 只要发布了每一个员工都能查看的到 所以在 表中插入每一个员工的id 和 当前广告的id  和 是否已读(都是0 还没发布)
        //获取所有员工的id
        List<Employee> employees = employeeMapper.selectAll();
        List<Long> empIdList = new ArrayList<>();
        for (Employee employee : employees) {
            empIdList.add(employee.getId());
        }
        noticeMapper.insertRelation(empIdList, notice.getId(), false);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo, Long id, boolean admin) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo, id, admin); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void updateStatus(Long id, Boolean status) {
        noticeMapper.updateStatus(id, status);
    }

    @Override
    public void updateIsRead(Long id, Long empId, boolean isRead) {
        noticeMapper.updateIsRead(id, empId, isRead);
    }

    @Override
    public Integer getUnread(Long id) {
        return noticeMapper.getUnread(id);
    }

    @Override
    public List<Notice> readCount() {
        return noticeMapper.readCount();
    }
}
